<?php
namespace app\admin\model;
use think\Model;

class Link extends Model
{

    protected static function init()
    {
        //添加之前的操作
        Link::event('before_insert',function($link){
          if($_FILES['pic']['tmp_name']){
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                if($info){
                    $pic=$info->getFileName();
                    $link['pic'] = "/static/uploads/".date('Ymd')."/".$pic;
                    // "C:\wamp\www\tp5\public\static\uploads\20170216\02472067b7a3352d793f7353096355da.jpg";
                    // var_dump($link['pic']);
                                    // die();
                }
            }
      });

        Link::event('before_update',function($link){
          if($_FILES['pic']['tmp_name']){
                $link=link::find($link->id);
                
                $thumbpath=$_SERVER['DOCUMENT_ROOT'].$link['pic'];
                if(file_exists($thumbpath)){
                    @unlink($thumbpath);
                }
                $file = request()->file('pic');
                // $info = $file->move(ROOT_PATH . 'public/uploads');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                if($info){
                    $pic=$info->getFileName();
                    $link['pic'] = "/static/uploads/".date('Ymd')."/".$pic;
                    db('link')->where('id',$link->data['id'])->update(['pic' => $link['pic']]);
                }

            }
      });

        Link::event('before_delete',function($link){         
                $link=link::find($link->id);
                $thumbpath=$_SERVER['DOCUMENT_ROOT'].$link['pic'];
                if(file_exists($thumbpath)){
                    @unlink($thumbpath);
                }
        });

    }

}
